package com.controller;

import com.entity.Buser;
import com.entity.table.BuserTableDef;
import com.service.BuserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @GetMapping("")
    public String index( Model model){
        return "back/index";
    }
//    登录成功，欢迎页面
    @GetMapping("/welcome")
    public String welcome( Model model){
        return "back/welcome";
    }
    @Resource
    BuserService bUserService;

    @GetMapping("/login")
    public String toLoginPage(){
        return "back/login";
    }
    //登录
    @PostMapping("/toLogin")
    public String login(Buser user, HttpSession httpSession, Model model){
        Buser bUser =   bUserService.queryChain().where(BuserTableDef.BUSER.USERNAME.eq(user.getUsername()))
                .and(BuserTableDef.BUSER.PASSWORD.eq(user.getPassword())).one();
        if (bUser!=null){
            // 将用户对象添加到Session
            bUserService.updateById(bUser);
            httpSession.setAttribute("admin", bUser);
            model.addAttribute("admin", bUser);//返回数据给前端页面
            // 跳转到主页面
            return "back/index";
//            return "redirect:/admin";
        }
        else {
            model.addAttribute("msg", "账号或密码错误，请重新输入！");
            return "back/login";
        }
    }
}
